//
// main.cpp -- Entry point for the package management tool, handles command-line arguments and calls corresponding package management functions.
//

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <nlohmann/json.hpp>
#include "json_utils.h"
#include "utils.h"
#include "tinybpt.h"
#include <sys/stat.h>
#include <cerrno>

int main(int argc, char *argv[]) {
    if (argc < 2) {
        print_help();
        return 1;
    }
    read_mirror(db_file);
    if (mkdir(download_path.c_str(), 0777) == -1 && errno != EEXIST) {
        std::cerr << "Failed to create download directory: " << download_path << ", error: " << strerror(errno) << std::endl;
        return 1;
    }
    std::string command = argv[1];
    if (command == "install") {
        if (argc < 3) {
            std::cout << "Please provide the package name to install\n";
            return 1;
        }
        std::string package_name = argv[2];
        std::string pkgs_url = config.mirror_url + "/" + config.target + "/" + config.arch + "/"+ config.dirs+ "/" ;
        install_package(package_name, pkgs_url);
    } else if (command == "uninstall") {
        if (argc < 3) {
            std::cout << "Please provide the package name to uninstall\n";
            return 1;
        }
        std::string package_name = argv[2];
        bool force = false;
        if (argc >= 4 && std::string(argv[3]) == "-f") {
            force = true;
        }
        remove_package(package_name, force);
    } else if (command == "list") {
        if (argc < 3) {
            std::cout << "Please provide an option: -all or -installed\n";
            return 1;
        }
        std::string list_type = argv[2];
        list_packages(list_type);
    } else if (command == "find") {
        if (argc < 3) {
            std::cout << "Please provide the package name to find\n";
            return 1;
        }
        std::string package_name = argv[2];
        std::cout << "Searching installed packages:\n";
        find_package(package_name, "localpackages");
        std::cout << "Searching all packages:\n";
        find_package(package_name, "packages");
    } else if (command == "-set-mirror") {
        if (argc < 3) {
            std::cout << "Please provide the mirror URL\n";
            return 1;
        }
        std::string new_mirror_url = argv[2];
        set_mirror_url(new_mirror_url, db_file);
    } else if (command == "-get-mirror") {
        show_mirror_url(db_file);
    } else if (command == "-version" || command == "-V") {
        show_version(db_file);
    } else if (command == "-help" || command == "-h" || command == "--help") {
        print_help();
    } else {
        std::cout << "Unknown command: " << command << "\n";
        print_help();
        return 1;
    }
    return 0;
}